package com.kinghood.productcenter.service.product.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinghood.infrastructure.api.authority.SysLogModuleEnum;
import com.kinghood.infrastructure.api.authority.UserRemoteVo;
import com.kinghood.infrastructure.model.dto.IdValueDTO;
import com.kinghood.infrastructure.util.UserUtil;
import com.kinghood.infrastructure.util.base.IdGenUtil;
import com.kinghood.infrastructure.util.excel.EasyExcelUtil;
import com.kinghood.productcenter.common.api.authority.UserRemote;
import com.kinghood.productcenter.common.model.dao.product.BusinessLogDO;
import com.kinghood.productcenter.common.model.dao.product.DownloadCenterDO;
import com.kinghood.productcenter.common.model.dto.product.BusinessLogQueryDTO;
import com.kinghood.productcenter.common.model.enums.product.BusinessLogOperateEnum;
import com.kinghood.productcenter.common.model.excel.BuinessLogExcel;
import com.kinghood.productcenter.common.model.excel.LabelExcel;
import com.kinghood.productcenter.common.model.vo.base.LabelListVO;
import com.kinghood.productcenter.common.model.vo.product.BuinessLogVO;
import com.kinghood.productcenter.common.utils.UserNameUtil;
import com.kinghood.productcenter.dao.product.BusinessLogMapper;
import com.kinghood.productcenter.service.product.IBusinessLogService;
import com.kinghood.productcenter.service.product.IDownloadCenterService;
import com.kinghood.productcenter.service.product.handler.ProductBaseHandler;
import com.kinghood.sharding.model.BasePage;
import com.kinghood.sharding.model.KingHoodPageUtil;
import com.kinghood.sharding.model.KingPageResult;
import com.kinghood.sharding.model.PageResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 业务日志表 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@Service
public class BusinessLogServiceImpl extends ServiceImpl<BusinessLogMapper, BusinessLogDO> implements IBusinessLogService {
    @Resource
    private UserRemote userRemote;
    @Value("${base.uploadPath}")
    private String uploadPath;
    @Resource
    private IDownloadCenterService downloadCenterService;

    /**
     * 业务日志列表
     *
     * @param param 参数
     * @return @return {@link PageResponseVO }
     * @author jp
     * @date 2024/01/12 14:58
     */
    @Override
    public PageResponseVO listBusinessLog(BusinessLogQueryDTO param) {
        if (!StringUtils.isEmpty(param.getOperator())) {
            List<Long> ids = userRemote.getIdListByNameOrAccount(param.getOperator());
            if (CollectionUtils.isEmpty(ids)) {
                return null;
            }
            param.setUserIdList(ids);
        }
        Page<BuinessLogVO> result = this.baseMapper.listBusinessLog(KingHoodPageUtil.getPage(param, param), param);

        Set<Long> userIdList = new HashSet<>();
        for (BuinessLogVO record : result.getRecords()) {
            userIdList.add(record.getCreateUserId());
            record.setOperateTxt(BusinessLogOperateEnum.getNameByType(record.getOperate()));
        }
        userIdList.remove(null);
        if (!CollectionUtils.isEmpty(userIdList)) {
            Map<Long, UserRemoteVo> userMap = userRemote.getUserByIds(new ArrayList<Long>(userIdList));
            for (BuinessLogVO record : result.getRecords()) {
                record.setCreateUserName(UserNameUtil.getName(record.getCreateUserId(), userMap));
            }
        }

        return KingPageResult.getResult(result);
    }

    /**
     * 列表业务日志操作类型
     *
     * @return @return {@link List }<{@link IdValueDTO }>
     * @author jp
     * @date 2024/01/12 14:58
     */
    @Override
    public List<IdValueDTO> listBusinessLogOperateType() {
        List<IdValueDTO> result = new ArrayList<>();
        for (BusinessLogOperateEnum module : BusinessLogOperateEnum.values()) {
            IdValueDTO idValueDTO = new IdValueDTO();
            idValueDTO.setId(module.getType());
            idValueDTO.setValue(module.getName());
            result.add(idValueDTO);
        }
        return result;
    }

    /**
     * 下载业务日志
     *
     * @param param    参数
     * @param response 回答
     * @return
     * @author jp
     * @date 2024/01/12 14:58
     */
    @Override
    public void downloadBusinessLog(BusinessLogQueryDTO param, HttpServletResponse response) {
        String fileName = StringUtils.isEmpty(param.getFileName()) ? "日志数据" : param.getFileName();
        String sheetName = StringUtils.isEmpty(param.getSheetName()) ? "日志" : param.getSheetName();

        if (Objects.isNull(param.getPage())) {
            param.setPage(new BasePage());
            param.getPage().setPageSize(99999);
        }
        PageResponseVO responseVO = listBusinessLog(param);
        List<BuinessLogVO> dataList = responseVO.getList();
        List<BuinessLogExcel> result = new ArrayList<>();
        for (BuinessLogVO listVO : dataList) {
            BuinessLogExcel excel = new BuinessLogExcel();
            BeanUtils.copyProperties(listVO, excel);
            result.add(excel);
        }
        // 保存到数据库
        LocalDateTime now = LocalDateTime.now();
        DownloadCenterDO downloadCenterDO = new DownloadCenterDO();
        try {
            String showParam = "";
            if (!CollectionUtils.isEmpty(param.getDownloadField())) {
                showParam = String.join(",", param.getDownloadField());
            }
            String path = EasyExcelUtil.export(response, fileName, sheetName, result, BuinessLogExcel.class,
                    showParam, uploadPath);
            File file = new File(path);

            int module = SysLogModuleEnum.PRODUCT_LABEL.getType();
            if (param.getBusinessType() == 2) {
                module = SysLogModuleEnum.PRODUCT_SKU.getType();
            }
            downloadCenterDO.setId(IdGenUtil.getId())
                    .setFileName(file.getName())
                    .setModule(module)
                    .setType(2)
                    .setFileSize(ProductBaseHandler.getSizeName(file.length()))
                    .setUrl(path)
                    .setCreateTime(now)
                    .setUpdateTime(now)
                    .setCreateUserId(UserUtil.getUserId())
                    .setUpdateUserId(UserUtil.getUserId());
            downloadCenterService.save(downloadCenterDO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
